#-*- coding:utf-8 -*-
"""
TabNode: 按Tab键弹出节点查询框
"""

import os
import sys
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *
from ..cgai import CGAI


class NodeList(QWidget):

    def __init__(self,GPATH,node_list,parent=None):
        """

        :param node_list: [node_data,node_data,...]
                node_data: {node_name:xx,node_id:xxx,node_icon:xxx}
        """
        super(NodeList, self).__init__()

        self.parent = parent
        self.GPATH = GPATH
        self.btn_style='''QToolButton{color:rgb(200,200,200)}
                                  QToolButton:hover{color:#FF7F24}
                                  QToolButton{background-color:rgb(75,75,75)}
                                  QToolButton{border:px}
                                  QToolButton{padding:5px 1px}'''
        # self.setFixedWidth(150)

        p=self.palette()
        p.setColor(QPalette.Base,QColor('#1C1C1C'))
        p.setColor(QPalette.Window, QColor('#393939'))
        p.setColor(QPalette.WindowText, QColor('#E8E8E8'))
        p.setColor(QPalette.Text,QColor('#1C1C1C'))
        self.setPalette(p)

        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(0)
        self.init_btns(node_list)

        self.setLayout(self.main_layout)

    def clip_list(self,origin_list, c):  # a为原列表，c为等分长度
        clip_back = []
        if len(origin_list) > c:
            for i in range(int(len(origin_list) / c)):
                clip_a = origin_list[c * i:c * (i + 1)]
                clip_back.append(clip_a)
            # last 剩下的单独为一组
            last = origin_list[int(len(origin_list) / c) * c:]
            if last:
                clip_back.append(last)
        else:  # 如果切分长度不小于原列表长度，那么直接返回原列表
            clip_back = [origin_list]

        return clip_back


    def init_btns(self,node_list):
        # layout_count = len(node_list)//10+1
        clips_layout = QHBoxLayout()
        node_clips = self.clip_list(node_list,10)

        for clip in range(len(node_clips)):
            btn_layout = QVBoxLayout()
            btn_layout.setAlignment(Qt.AlignTop)
            btns = node_clips[clip]
            for i in btns:
                btn = QToolButton()
                btn.setText(i['node_label'])
                btn.setProperty('node_name', i['node_name'])
                btn.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
                icon_path = os.path.join(self.GPATH, 'Nodes', i['node_module'], 'icons', i['node_icon'])
                btn.setIcon(QIcon(icon_path))
                # btn.setIcon(QIcon('a.png'))
                btn.setStyleSheet(self.btn_style)
                btn.clicked.connect(self._create_node)
                # self.main_layout.addWidget(btn)
                btn_layout.addWidget(btn)
            clips_layout.addLayout(btn_layout)

        self.main_layout.addLayout(clips_layout)
        # for i in node_list:
        #
        #     btn = QToolButton()
        #     btn.setText(i['node_label'])
        #     btn.setProperty('node_name',i['node_name'])
        #     btn.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        #     icon_path = os.path.join(self.GPATH,'Nodes',i['node_module'],'icons',i['node_icon'])
        #     btn.setIcon(QIcon(icon_path))
        #     # btn.setIcon(QIcon('a.png'))
        #     btn.setStyleSheet(self.btn_style)
        #     btn.clicked.connect(self._create_node)
        #     self.main_layout.addWidget(btn)

    def _create_node(self):
        sender = self.sender()
        node_name = sender.property('node_name')
        print(node_name)
        self.parent.close()



class TabWindow(QWidget):
    node_itype_Signal=Signal('str')
    def __init__(self,data_list):
        super(TabWindow, self).__init__()

        self.node_list = ['a','b','c','d','e','f',
                          'aa','bb','cc','dd','ee','ff',
                          'aaa','bbb','ccc','ddd','eee','fff']
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setStyleSheet(
            'QWidget{background-color:rgb(75,75,75);color:rgb(200,200,200)}'
            'QLabel{background-color:rgb(75,75,75); color:rgb(200,200,200)}'
         )
        self.main_layout=QVBoxLayout()
        self.main_layout.setAlignment(Qt.AlignTop)
        self.show_label=QLabel('Nodes')
        self.node_edit=QLineEdit()
        completer=QCompleter(data_list)
        completer.setCompletionMode(QCompleter.PopupCompletion)
        self.node_edit.setCompleter(completer)

        self.mz_menu = self.init_menu()


        self.main_layout.addWidget(self.show_label)
        self.main_layout.addWidget(self.node_edit)
        self.main_layout.addWidget(self.mz_menu)
        self.setLayout(self.main_layout)

    def init_menu(self):
        mz_menu = QMenu()
        menu_style ='QMenu{background-color:rgb(75,75,75); color:rgb(200,200,200)};border:0px;padding:0px'

        pandas_menu = QMenu('Pandas', self)
        pandas_menu.setStyleSheet(menu_style)
        pd_apply_action = QWidgetAction(pandas_menu)
        # pd_apply_action.setProperty('canHideMenu','false')
        pd_apply_action.setCheckable(False)
        node_list = [{'node_id': 1, 'node_name': 'pd_apply','node_module':'pandas',
                      'node_label': 'Apply', 'node_icon': 'apply.png', 'node_func': None}]
        g_path = CGAI.GPATH
        pd_list = NodeList(g_path,node_list*50, self)

        pd_apply_action.setDefaultWidget(pd_list)
        # pd_apply_action.setIcon(QIcon('a.png'))
        # pd_apply_action.triggered.connect(self._create_node)
        pandas_menu.addAction(pd_apply_action)
        mz_menu.addMenu(pandas_menu)

        tf_menu = QMenu('Tensoflow',self)
        tf_menu.setStyleSheet(menu_style)
        tf_action = QWidgetAction(tf_menu)
        tf_list = NodeList(g_path,node_list*32,self)
        tf_action.setDefaultWidget(tf_list)
        tf_menu.addAction(tf_action)
        mz_menu.addMenu(tf_menu)


        return mz_menu
    
    def _create_node(self):
        pass

    def keyPressEvent(self, QKeyEvent):
        if QKeyEvent.key() ==Qt.Key_Return:
            self.node_itype_Signal.emit(self.node_edit.text())
            self.close()
            
    # def focusOutEvent(self, *args, **kwargs):
    #     self.close()

if __name__ == '__main__':
    app=QApplication(sys.argv)
    data=['a','aa1','bb','c1','b2','cc']
    t=TabWindow(data)
    t.show()
    sys.exit(app.exec_())